package com.powerunion.datacollection.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.powerunion.datacollection.common.SystemException;
import com.powerunion.datacollection.dao.DaoFactory;
import com.powerunion.datacollection.dao.FormFieldDao;
import com.powerunion.datacollection.model.FormField;
import com.powerunion.datacollection.model.jsonObject.JSONDataBean;
import com.powerunion.util.log.LogHelper;

public class FormFieldManager {
	private static Logger logger = LogHelper.getInstance().getLogger(FormFieldManager.class);
	private FormFieldDao dao = null;
	public FormFieldManager() {
		super();
		this.dao = (FormFieldDao)DaoFactory.getInstance().getDao(FormFieldDao.class);
	}
	
	public boolean save(String formFieldsStr,String formId) throws Exception{
		//参数为空
		if(StringUtils.isEmpty(formFieldsStr)) {
			String[] args = { "formFieldsStr" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter formFieldsStr NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}

		//先删除原有的信息再保存
		this.dao.delete(formId);
		
		Map classMap = new HashMap();  
		classMap.put("data", FormField.class);
		JSONDataBean cl = (JSONDataBean)JSONObject.toBean(JSONObject.fromObject(formFieldsStr), JSONDataBean.class,classMap);
		
		return this.dao.save(cl.getData(),formId);

	}
	
	public FormField findByKey(String id){
		//参数为空
		if(StringUtils.isEmpty(id)) {
			String[] args = { "id" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter id NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		
		return this.dao.getBykey(id);
	}
	
	public String getFormFields(String formId) throws Exception{
		List fieldFields = this.dao.getFormFields(formId);
		JSONArray jsonArr = JSONArray.fromObject(fieldFields);
		String result = "{results:"+jsonArr+"}";
		return result;
	}
	
	public List getFormFieldsList(String formId) throws Exception{
		//参数为空
		if(StringUtils.isEmpty(formId)) {
			String[] args = { "formId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter formId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		return this.dao.getFormFields(formId);
	}
	
	public String getServers() throws Exception {
		StringBuffer result = new StringBuffer();
		List servers = this.dao.getServers();
		// 转化成JSON数组
		JSONArray jsonarr = JSONArray.fromObject(servers);
		result.append("{results:")
		.append(jsonarr).append("}");
		
		return result.toString();
	}
	
}
